﻿using Model;
using Model.Modules;
using Nest;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Model;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Threading;
using Utility;
using Proxy;

namespace ViewModel
{
    public class VM_PageAnalysis : BaseViewModel
    {

        #region 变量
        public static surfacedetectEntities surfaceEntities;


        public DateTime Start { get { return start; } set { start = value; OnPropertyChanged(); } }
        private DateTime start;
        public DateTime End { get { return end; } set { end = value; OnPropertyChanged(); } }
        private DateTime end;

        public ICollectionView GridSource { get { return gridSource; } set { gridSource = value; OnPropertyChanged(); } }
        private ICollectionView gridSource;


        public ObservableCollection<steeldefectinfo> SteelDefectlist { get { return steeldefectlist; } set { steeldefectlist = value; OnPropertyChanged(); } }
        private ObservableCollection<steeldefectinfo> steeldefectlist;


        public string Message { get { return message; } set { message = value; OnPropertyChanged(); } }
        private string message;

        public bool Complated { get; set; }

        

        public int CurrentImageIndex
        {
            get { return currentImageIndex; }
            set
            {
                currentImageIndex = value;
                OnPropertyChanged();
                //imagesFactory.UpdateImage(CurrentImageIndex);
            }
        }
        private int currentImageIndex;


        public Imagedefectinfo CurrentImg
        {
            get { return currentImg; }
            set
            {
                currentImg = value; OnPropertyChanged();
            }
        }
        private Imagedefectinfo currentImg;





        ESDataHelper eshelper;
        ImagesVirtualFactory imagesFactory;
        bool isInit = false;
        TestEntitity testEntitity;
        #endregion
        //CancellationTokenSource source = new CancellationTokenSource();
        Stack<CancellationTokenSource> sourcestack = new Stack<CancellationTokenSource>();
        bool hasqueryotherpage = false;
        public VM_PageAnalysis()
        {
            InitData();

        }

        private void InitData()
        {

            surfaceEntities = new surfacedetectEntities();
            Start = DateTime.Now.AddDays(-2);
            End = DateTime.Now;
            Logger.Info("SuccessInitHistoryData");
            isInit = true;
            Complated = true;
            Task.Run(() =>
            {
                //QuerySource();
            });

        }
        private void QuerySource()
        { 
            Task.Run(() =>
            {
                AsyncQuerySource();
            });
        }
        private Task AsyncQuerySource()
        {
            DoMenthodByDispatcher(() =>
            {
                Complated = false;
                Message = $"正在查询请稍候";
            });
            var types = StaticData.DefectTypes;
            DataTable dt = new DataTable();
            //永刚用main_id和user_custom_id，显示user_custom_id，兴澄用main_id
            dt.Columns.Add(new DataColumn("main_id", typeof(string)));
            dt.Columns.Add(new DataColumn("user_custom_id", typeof(string)));
            dt.Columns.Add(new DataColumn("insert_time", typeof(DateTime)));
            dt.Columns.Add(new DataColumn("cz", typeof(string)));
            dt.Columns.Add(new DataColumn("gg", typeof(string)));
            dt.Columns.Add(new DataColumn("grade", typeof(string)));
            dt.Columns.Add(new DataColumn("score", typeof(string)));
            dt.Columns.Add(new DataColumn("defect_img_ratio", typeof(string)));
            foreach (var type in types)
            {
                //dt.Columns.Add(new DataColumn(type.id.ToString(), typeof(string)));
                dt.Columns.Add(new DataColumn(type.id.ToString() + "_alert", typeof(string)));
                dt.Columns.Add(new DataColumn(type.id.ToString() + "_warning", typeof(string)));
                dt.Columns.Add(new DataColumn(type.id.ToString() + "_suspected", typeof(string)));
            }
            try {
                var filteredBatches = surfaceEntities.batch
                    .Where(batch => batch.insert_time > Start && batch.insert_time < End)
                    .OrderByDescending(batch => batch.insert_time).ToList();
                Stopwatch st = new Stopwatch();
                st.Start();
                var result = from batch in filteredBatches
                             where batch.insert_time > Start && batch.insert_time < End
                             orderby batch.insert_time descending
                             from defectType in surfaceEntities.defect_type
                             where defectType.isdetectout == true
                             join sda in surfaceEntities.steel_defect_amout
                             on new { batchid = batch.main_id, defecttype = defectType.id } equals new { batchid = sda.main_id, defecttype = sda.defect_type } into gj
                             from sub in gj.DefaultIfEmpty()
                             select new
                             {
                                 BatchId = batch.main_id,
                                 User_custom_id = batch.user_custom_id,
                                 InsertTime = batch.insert_time,
                                 CZ=batch.cz,
                                 GG=batch.gg,
                                 DefectTypeId = defectType.id,
                                 Grade = batch.grade,
                                 Score = batch.score,
                                 Ratio = batch.defect_img_ratio,
                                 DefectCount = sub == null ? 0 : sub.defect_num,
                                 WarningCount = sub == null ? 0 : sub.warn_num,
                                 AlertCount = sub == null ? 0 : sub.alert_num,
                                 SuspectedCount = sub == null ? 0 : sub.suspected_num,
                             };
                var distinctResult = result.GroupBy(r => new { r.BatchId, r.DefectTypeId })
                           .Select(g => g.First());

                Logger.Info($"查询到{result.Count()}条记录,用时{st.Elapsed}");

                DoMenthodByDispatcher(() =>
                {
                    Message = $"查询完成，正在统计，预计还需要{st.Elapsed.TotalSeconds*2:F2}秒";
                });
                distinctResult.GroupBy(t => t.BatchId).Select(t => new { t.Key, t }).ToList().ForEach(t =>
                {
                    DataRow dr = dt.NewRow();
                    List<object> drarray = new List<object> { };
                    drarray.Add(t.Key);//批次号
                    drarray.Add(t.t.First().User_custom_id);//批次号
                    drarray.Add(t.t.First().InsertTime);//插入时间
                    drarray.Add(t.t.First().CZ);//材质
                    drarray.Add(t.t.First().GG);//规格
                    drarray.Add(t.t.First().Grade);//分级
                    drarray.Add(t.t.First().Score);//分数
                    drarray.Add(t.t.First().Ratio);//缺陷图片占比
                    var sortedlist = t.t.OrderBy(o => o.DefectTypeId);
                    foreach (var typeinfo in sortedlist)
                    {
                        drarray.Add(typeinfo.AlertCount != 0 ? typeinfo.AlertCount.ToString() : "");
                        drarray.Add(typeinfo.WarningCount != 0 ? typeinfo.WarningCount.ToString() : "");
                        drarray.Add(typeinfo.SuspectedCount != 0 ? typeinfo.SuspectedCount.ToString() : "");
                    }
                    dt.Rows.Add(drarray.ToArray());
                });
                Logger.Info($"解析完成{dt.Rows.Count}条记录,用时{st.Elapsed}");
                //var ddd=result.ToList();
                //var batchs = surfaceEntities.batch.AsNoTracking().Where(t=>t.insert_time>=Start&&t.insert_time<=End).OrderByDescending(t=>t.insert_time).ToList();
                //foreach (var batch in batchs)
                //{
                //    try
                //    {


                //    DataRow dr=dt.NewRow();
                //    List<object> drarray = new List<object> { };
                //    drarray.Add(batch.main_id);
                //    drarray.Add(batch.insert_time);
                //    drarray.Add(batch.grade);
                //    Dictionary<string, string> typecoutlist = new Dictionary<string, string>();
                //    if (string.IsNullOrEmpty(batch.conclusion))
                //        continue;
                //    foreach (var item in batch.conclusion.Split('\n'))
                //    {
                //        if (item.Length > 0)
                //        {
                //            var typevalue = item.Split(':');
                //            typecoutlist.Add(typevalue[0].Replace("-", ""), typevalue[1]);
                //        }
                //    }
                //    foreach (var type in types)
                //    {
                //        var typeinfo = typecoutlist.Where(t => t.Key == type.id.ToString());
                //        drarray.Add(typeinfo.Any() ? typeinfo.First().Value.Trim('\r') : "");
                //    }

                //    dt.Rows.Add(drarray.ToArray());
                //    }
                //    catch
                //    {

                //    }
                //}
                DoMenthodByDispatcher(() =>
                {
                    ICollectionView collectionView = CollectionViewSource.GetDefaultView(dt);
                    GridSource = collectionView;
                    Complated = true;
                    Message = "";
                });
            }
            catch (Exception ee) {
                Logger.Error(ee);
            }
            finally
            {
                DoMenthodByDispatcher(() =>
                {
                    Complated = true;
                    Message = "";
                });
            }

            return Task.CompletedTask;
        }

        /// <summary>
        /// 使用dynamic根据DataTable的列名自动添加属性并赋值
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns> 
        public static Object GetDynamicClassBydt(IList<defect_type> types)
        {
            dynamic d = new System.Dynamic.ExpandoObject();
            //创建属性，并赋值。
            foreach (defect_type type in types)
            {
                (d as System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string, object>>).Add(new System.Collections.Generic.KeyValuePair<string, object>("t" + type.id.ToString(), type.name.ToString()));
            }
            return d;
        }

        public BaseCommand SearchCommand { get => new BaseCommand(SearchCommand_Executed); }
        public void SearchCommand_Executed(object obj)
        {
            QuerySource();
        }

        public BaseCommand SearchBatchCommand { get => new BaseCommand(SearchBatchCommand_Executed); }
        public void SearchBatchCommand_Executed(object obj)
        {
            QueryBatchList();
        }
        private void QueryBatchList()
        {


        }

        public BaseCommand ConfigCommand { get => new BaseCommand(ConfigCommand_Executed); }
        public void ConfigCommand_Executed(object obj)
        {
            new VM_WindowGradeConfig().ShowDialog();
        }

        public BaseCommand AddCusotmIdCommand { get => new BaseCommand(AddCusotmIdCommand_Executed); }
        public void AddCusotmIdCommand_Executed(object obj)
        {


        }

        public BaseCommand SubTotalCommand
        {
            get => new BaseCommand((obj) =>
            {
                QuerySource();

            });
        }



    }
}
